package com.tianqu.tms.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.tianqu.tms.core.exception.TmsDaoException;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.dto.TmsCarmodelVinDto;

public class TmsCarmodelVinDaoImp  extends ViewListDao implements TmsCarmodelVinDao {

	protected TmsCarmodelVinDaoImp() throws TmsDaoException {
		super();
	}

	@Override
	public TmsCarmodelVinDto get(String modelId,String vin) throws TmsDaoException {
		PreparedStatement ps = null;
		ResultSet rs = null;
		TmsCarmodelVinDto dto = null;
		int i = 1;
		try {
			conn = super.getConnection();
			StringBuffer sql = new StringBuffer();
			sql.append("SELECT MODELID, ");
			sql.append("VIN ");
			sql.append("FROM ");
			sql.append(TmsTableNames.TMS_CARMODEL_VIN);
			sql.append(" WHERE ");
			sql.append(" 1=1 ");
			if(!StringUtil.isNullOrBlank(modelId)) sql.append(" AND MODELID=? ");
			if(!StringUtil.isNullOrBlank(vin))  sql.append(" AND VIN=? ");

			ps = conn.prepareStatement(sql.toString());
			if(!StringUtil.isNullOrBlank(modelId)) ps.setString(i++, modelId);
			if(!StringUtil.isNullOrBlank(vin))  ps.setString(i++, vin);
			
			// 执行sql
			rs = ps.executeQuery();

			while (rs.next()) {
				dto = new TmsCarmodelVinDto();
				dto.setModelId(rs.getString("MODELID"));
				dto.setVin(rs.getString("VIN"));
			}
		} catch (SQLException e) {
			throw new TmsDaoException(e.toString());
			
		} finally {
			close(rs,ps);
		}
		return dto;
	}

	@Override
	public void insert(TmsCarmodelVinDto dto) throws TmsDaoException {
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			StringBuffer sql = new StringBuffer("INSERT INTO ");
			sql.append(TmsTableNames.TMS_CARMODEL_VIN);
			sql.append("(");
			sql.append(" MODELID, ");
			sql.append(" VIN");
			sql.append("  ) VALUES ( ");
			sql.append(" ?,?)");
			ps = conn.prepareStatement(sql.toString());
			ps.setString(1, dto.getModelId());
			ps.setString(2, dto.getVin());
			ps.executeUpdate();
			
		} catch (SQLException e) {
			throw new TmsDaoException(e.toString());

		} finally {
			super.close(rs, ps);
		}
	}

	@Override
	public void update(TmsCarmodelVinDto bean) throws TmsDaoException {
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			StringBuffer sql = new StringBuffer("  UPDATE	");
			sql.append(TmsTableNames.TMS_CARMODEL_VIN);
			sql.append(" SET ");
			sql.append(" MODELID=? ");
			sql.append(" WHERE ");
			sql.append(" VIN=? ");
			ps = conn.prepareStatement(sql.toString());
			ps.setString(1, bean.getModelId());
			ps.setString(2, bean.getVin());
			ps.executeUpdate();
		} catch (SQLException e) {
			throw new TmsDaoException(e.toString());

		} finally {
			super.close(rs, ps);
		}
	}

}
